// GLSL 文件加载 

export default class GLSLLoader {

	static findShader(shader_name:string, array:any[]) {

		let object = array.find(value => {

			return value.name.includes(shader_name);

		})

		object = object !== undefined ? object : { shader: null };

		return object.shader;

	}

	// 加载单个着色器文件
	static loadShader(url) {

		return new Promise(function (resolve, reject) {

			GLSLLoader.loader(url, function (response) {

				resolve(response);

			}, function (error) {

				reject(error)

			})

		})

	}

	// 加载文件数组
	static loadArrays(arrays, onload) {

		if (!(arrays instanceof Array)) {
			console.warn('variable is not Array');
		}

		let results = [];

		
		arrays.forEach(values => {

			GLSLLoader.loadShader(values).then(data => {

				// 以对象的形式返回着色器代码
				results.push({
					name: values, shader: data
				});

				if (results.length === arrays.length) {
					onload(results);
				}

			})

		})

	}

	// 加载两个着色器文件
	static loadVertexFragment(urls, onLoad, onError) {

		let shader:any = {};

		if ((typeof urls) == 'string') {

			urls = [urls];

		}

		urls.forEach(values => {

			GLSLLoader.loadShader(values).then(function (data:any) {

				let fragment = data.includes('gl_FragColor');

				if (fragment) {
					shader.fragment = data;
				} else {
					shader.vertex = data;
				}

				if (shader.vertex && shader.fragment) onLoad(shader);

			}, function (error) {

				onError(error)

			})

		});

	}



	static loader(url, onLoad, onError) {

		if (!url) console.warn('url is error or is undefined...');

		let xhr = new XMLHttpRequest();

		xhr.open('GET', url, true);

		xhr.addEventListener('load', function (event) {

			let responseText = this.responseText;

			if (this.status !== 200) {

				onError(event);

			} else {

				// 通过正则表达式去掉注释
				responseText = responseText.replace(/(\n)|(\/{2,}.*?(\r|\n))|(\/\*(\n|.)*?\*\/)/g, '');

				onLoad(responseText);

			}

		}, false);

		xhr.addEventListener('error', function (event) {

			onError(event);

		}, false);

		xhr.send(null);

	}
}



